<?php

namespace App\Http\Controllers\AuthAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\Admin;
use Crypt;
use Auth;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/admin/login';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * 密码验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function checkPwdValidator(array $data){
        $attribute =  array(
            'password' => '密码',
        );

        $message  = array(
            'required' => ':attribute必须填写',
            'confirmed' => ':attribute不相同',
            'min' => '最小:min字符',
            'max' => '最大:max字符',
        );
        return Validator::make($data, [
           'password' => 'required|confirmed|min:6|max:15',
        ],$message,$attribute);
    }

    /**
     * 密码重置
     * @return [type] [description]
     */
    public function reset(Request $request){
        $validator = $this->checkPwdValidator($request->all());
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
 
        Admin::where(['id'=>$this->guard()->user()->id])->update(['password'=>bcrypt($request->input('password'))]);

        $this->guard()->logout();
        $request->session()->flush();
        $request->session()->regenerate();
        return $this->ajaxJson(0,'重置成功',[],false);
    }

    protected function guard()
    {
        return Auth::guard('admin');
    }
}
